<template>
	<a-spin :spinning="isLoading">
		<page-layout>
			<a-form ref="formRef" :model="formState.state">
				<a-row :gutter="[10, 10]">
					<footer-button :buttons="formState.buttons" />
					<a-col :span="24">
						<div class="pre-title">{{t('order-manage.title.studentInformation')}}</div>
						<a-card>
							<a-row :gutter="[16,16]">
								<a-col :span="5">
									<a-form-item :label="t('order-manage.label.stuName')" name="stuName">{{formState.state.stuName}}
									</a-form-item>
								</a-col>
								<a-col :span="5">
									<a-form-item :label="t('order-manage.title.stuuniversity')">
										{{formState.state.colName}}
									</a-form-item>
								</a-col>
								<a-col :span="5">
									<a-form-item :label="t('order-manage.title.stuzjNum')">{{formState.state.paperNum}}
									</a-form-item>
								</a-col>
								<a-col :span="5">
									<a-form-item :label="t('order-manage.title.urgPhone')">{{formState.state.localPhone}}
									</a-form-item>
								</a-col>
							</a-row>
							<a-row type="flex" justify="end">
								<a-button type="primary" @click="openDialog('student')">
									{{t('order-manage.title.selectstu')}}
								</a-button>
							</a-row>
						</a-card>
						<div class="pre-title">{{t('order-manage.title.RegistrationInformation')}}</div>
						<a-card>
							<a-row class="list_t" :gutter="[16,16]">
								<a-col :span="5">
									<a-form-item>{{t('order-manage.openDialog.projectName')}}</a-form-item>
								</a-col>
								<a-col :span="5">
									<a-form-item>{{t('order-manage.openDialog.semester')}}</a-form-item>
								</a-col>
								<a-col :span="5">
									<a-form-item>{{t('order-manage.openDialog.courseName')}}</a-form-item>
								</a-col>
								<a-col :span="5">
									<a-form-item>{{t('order-manage.openDialog.price')}}</a-form-item>
								</a-col>
								<a-col :span="4">
									<a-form-item>{{t('button.operation')}}</a-form-item>
								</a-col>
							</a-row>
							<a-row :gutter="[16,16]" class="list_t" v-for="(item,index) in formState.state.orderCourseList" :key="index">
								<a-col :span="5">
									<a-form-item>{{item.projectName}}</a-form-item>
								</a-col>
								<a-col :span="5">
									<a-form-item>{{item.semesterName}}</a-form-item>
								</a-col>
								<a-col :span="5">
									<a-form-item>{{item.courseName}}</a-form-item>
								</a-col>
								<a-col :span="5">
									<a-form-item>{{item.price}}</a-form-item>
								</a-col>
								<a-col :span="4">
									<a-button type="danger" @click="detele(index)">{{t('button.delete')}}</a-button>
								</a-col>
							</a-row>
							<a-row type="flex" justify="end">
								<a-button type="primary" @click="openDialog('course')">
									{{t('order-manage.openDialog.selectcourse')}}
								</a-button>
							</a-row>
						</a-card>
						<div class="pre-title">{{t('order-manage.title.saleinfo')}}</div>
						<a-card>
							<a-row class="list_t">
								<a-col :span="5">
									<a-form-item>{{t('order-manage.title.salepolicy')}}</a-form-item>
								</a-col>
								<a-col :span="5">
									<a-form-item>{{t('order-manage.title.policyType')}}</a-form-item>
								</a-col>
								<a-col :span="5">
									<a-form-item>{{t('order-manage.title.salepricenum')}}</a-form-item>
								</a-col>
								<a-col :span="4">
									<a-form-item>{{t('button.operation')}}</a-form-item>
								</a-col>
							</a-row>
							<a-row class="list_t" v-for="(item,index) in formState.state.orderPolicyList" :key="index">
								<a-col :span="5">
									<a-form-item>{{item.policyName}}</a-form-item>
								</a-col>
								<a-col :span="5">
									<a-form-item>{{formatter(item.preType)}}</a-form-item>
								</a-col>
								<a-col :span="5">
									<a-form-item>{{item.policyAmount}}</a-form-item>
								</a-col>
								<a-col :span="4">
									<a-button type="danger" @click="detelesale(index)">{{t('button.delete')}}</a-button>
								</a-col>
							</a-row>
							<a-row type="flex" justify="end">
								<a-button type="primary" @click="openDialog('sale')">
									{{t('order-manage.title.selfavouredpolicy')}}
								</a-button>
							</a-row>
						</a-card>
						<!-- 特殊优惠信息 -->
						<div class="pre-title">{{t('order-manage.title.Paymentinformation')}}</div>
						<a-card>
							<!-- <a-row>
								<a-col :span="8">
									<a-form-item :label="t('order-manage.title.Paymentmethod')" :labelCol="{ span: 6 }"
										:wrapperCol="{ span: 18 }" name="payStatus">
										<a-radio-group v-model:value="formState.state.payStatus">
											<a-radio value="3">{{t('order-manage.title.Fullpayment')}}</a-radio>
											<a-radio value="2">{{t('order-manage.title.Deposit')}}</a-radio>
										</a-radio-group>
									</a-form-item>
								</a-col>
								<a-col :span="8" v-if='formState.state.payStatus==2'>
									<a-form-item name="recAmt">
										<a-input :placeholder="t('order-manage.title.inDeposit')" v-model:value="formState.state.recAmt"/>
									</a-form-item>
								</a-col>
							</a-row> -->
							<a-row>
								<a-col :span="8">
									<a-form-item :label="t('order-manage.title.is_t_sale')" :labelCol="{ span: 6 }"
										:wrapperCol="{ span: 18 }" name="isSpecial">
										<a-radio-group v-model:value="formState.state.isSpecial">
											<a-radio v-for="item in dictLists.data['yerOrON']" :key="item.id"
												:value="item.value">
												{{ item.label }}
											</a-radio>
										</a-radio-group>
									</a-form-item>
								</a-col>
								<a-col :span="8" v-if='formState.state.isSpecial==1'>
									<a-form-item name="specialAmt" :rules="{ required: false, validator: validatorSprice, trigger: 'change'}">
										<a-input :placeholder="t('order-manage.title.saleprice')"
											v-model:value="formState.state.specialAmt" />
									</a-form-item>
								</a-col>
							</a-row>
						</a-card>
						<a-card>
							<a-row>
								<!-- 课程总价 -->
								<a-col :span="6">
									<a-form-item :label="t('order-manage.title.Totalcourse')" class="red">
										{{formState.state.totalAmt}}
									</a-form-item>
								</a-col>
								<!-- 优惠总金额 -->
								<a-col :span="6">
									<a-form-item :label="t('order-manage.title.Totalpreferentia')" class="red">
										{{formState.state.discountAmt || 0}}
									</a-form-item>
								</a-col>
								<!-- 应付总额 -->
								<a-col :span="6">
									<a-form-item :label="t('order-manage.title.Totalpayable')" class="red">
										{{formState.state.receivableTotalAmt}}
									</a-form-item>
								</a-col>
							</a-row>
						</a-card>
					</a-col>
				</a-row>
			</a-form>
			<BasicTableModal v-model:visible="modalConfig.show" v-if="modalConfig.show"
				:columns="modalConfig.commonColumns" :fetchAjax="modalConfig.api" :title="modalConfig.title"
				:searchForm="modalConfig.searchForm" :searchParams="modalConfig.searchParams"
				:isPagination="modalConfig.isPagination"
				:selection="modalConfig.selection"
				:checkedKeys="modalConfig.keys"
				:okText="modalConfig.okText"
				@selectUniversity="value => selectItem(value,modalConfig.currentType)" />
		</page-layout>
	</a-spin>
</template>
<script>
export default {
	name: "order-manage-add"
}
</script>
<script setup>
	import {
		save,
		selectById,
		update,
		salepage,
		depositPage,
		coursePage
	} from "@/api/module/student/order-manage";
	import {
		onMounted,
		reactive,
		ref,
		toRaw,
		onActivated,
    computed
	} from "vue";
	import {
		useRoute,
		useRouter
	} from 'vue-router'
	import {
		getDictByCodesReturnObj
	} from '@/tools/get-dict'
	import dictEnum from '@/const/dict'
	import {
		page as studentpage
	} from '@/api/module/student/student-bop-manage'
	import {
		page as schoolPage
	} from '@/api/module/school'
	import BasicTableModal from '@/component/basic-table-modal'

	import {
		page as userPage
	} from '@/api/module/user'

	import {
		message, Result
	} from "ant-design-vue";
	import {
		upload
	} from "@/api/module/oss"
	import moment from 'moment';
	import {
		useI18n
	} from "vue-i18n";
import { watch } from "fs";
	const {
		t
	} = useI18n();
	let isLoading = ref(false)
	const formRef = ref();
	const route = useRoute()
	const router = useRouter()
	const formState = reactive({
		buttons: [{
				name: 'save',
				event: () => onSubmit(),
				type: "primary",
				code: ''
			},
			{
				name: 'reset',
				event: () => resetForm(),
				code: ''
			}
		],
		data: {
			stuName: '',
			colName: '',
			localPhone: '',
			paperNum: '',
			orderPolicyList: [],
		},
		state: {
			stuName: '',
			colName: '',
			localPhone: '',
			paperNum: '',
			orderPolicyList: [],
			buspId: '',
			isSpecial: '0',
			orderCourseList: [],
			orderType: '手工录入',
			payChn: "2",
			status: '0',
			recAmt:'',//定金金额
			specialAmt: '', //特殊优惠金额
			prePolicy: '', //优惠政策
			totalAmt: '0', //课程总价,
			preAmt: '0', //优惠总金额,
			receivableTotalAmt: '0', //应收金额
		}
	});
	const saveKey = "save";
	formState.state.totalAmt = computed(() => {
		let result = 0
		let arr = formState.state.orderCourseList || []
		arr.forEach(function(value) {
			result += value.price
		})
		return result || 0
	})
	formState.state.discountAmt = computed(() => {
		let result = 0
		let arr = formState.state.orderPolicyList || []
		arr.forEach(function(value) {
			result += value.policyAmount
		})
		return result || 0
	})
	formState.state.receivableTotalAmt = computed(() => {
		let { totalAmt, discountAmt, specialAmt } = formState.state
		console.log('totalAmt, discountAmt, specialAmt: ', totalAmt, discountAmt, specialAmt);
		const price = Number(totalAmt) - Number(discountAmt) - Number(specialAmt)
		return price
	})
	const labelCol = {
		span: 6
	}
	const wrapperCol = {
		span: 18
	}
	let dictLists = reactive({
		data: {}
	})
	const modalConfig = reactive({
		isPagination: true,
		title: '选择学校',
		api: '',
		show: false,
		selection: false,
		currentType: '',
		keys: [],
		okText: '关闭',
		commonColumns: [],
		universityColumns: [],
		responsibleColumns: [],
		searchForm: [],
		searchParams: [],
		studentSearchForm: [{
			label: t('order-manage.label.stuName'),
			key: 'stuName',
			type: 'input',
			placeholder: t('placeholder.pleaseEnter')
		}],
		courseSearchForm: [
			{
				label: '学校名称',
				key: 'schName',
				type: 'input',
				placeholder: t('placeholder.pleaseEnter'),
				hidden: true
			},
			{
				label: '项目名称',
				key: 'projectName',
				type: 'input',
				placeholder: t('placeholder.pleaseEnter'),
				hidden: true
			},
			{
				label: '学期',
				key: 'semesterName',
				type: 'input',
				placeholder: t('placeholder.pleaseEnter'),
				hidden: true,
			},
			{
				label: t('order-manage.openDialog.courseName'),
				key: 'courseName',
				type: 'input',
				placeholder: t('placeholder.pleaseEnter')
			},
		],
		saleSearchForm: [],
	})
	const formRules = {
		contactsName: [{
			required: true,
			message: '请输入联系人姓名',
			trigger: 'blur'
		}],
		contactsDepartment: [{
			required: true,
			message: '请输入所属部门',
			trigger: 'blur'
		}]
	};
	onActivated(async() => {
		const { id } = route.query
		if (id) {
			const response = await selectById({id})
			if (response.code == 500 || !response.data) message.warning('获取详情失败')
			response.data.orderPolicyList = response.data.orderPolicyList || []
			formState.state = response.data
			formState.state.buspId = response.data.stuBusp.id,
			formState.state.stuName = response.data.stuBusp.stuName,
			formState.state.colName = response.data.stuBusp.colName,
			formState.state.paperNum = response.data.stuBusp.paperNum,
			formState.state.localPhone = response.data.stuBusp.localPhone
			console.log('formState.state: ', formState.state);
		}
	})
	onMounted(async () => {
		dictLists.data = await getDictByCodesReturnObj([
			dictEnum.CLASS_STATUS,
			dictEnum.PAY_STATUS,
			dictEnum.FOLLOW_PROGRESS,
			dictEnum.YEARS,
			dictEnum.SEMESTER,
			dictEnum.QUARTER,
			dictEnum.YES_OR_NO,
			dictEnum.CURRENCY,
			dictEnum.PAY_TYPE,
			dictEnum.RECNAME,
			dictEnum.RECAMT,
			dictEnum.PRE_TYPE,
			dictEnum.COURSE_TYPE,
		])
		modalConfig.studentColumns = [{
				dataIndex: "stuName",
				key: "stuName",
				title: t('order-manage.label.stuName')
			},
			{
				dataIndex: "colName",
				key: "colName",
				title: t('order-manage.label.school')
			},
			{
				dataIndex: "colBtime",
				key: "colBtime",
				title: t('order-manage.label.colBtime'),
				cellRender: (record, data) => {
					if (data) {
						return moment(data).format('YYYY-MM-DD')
					}
				}
			},
			{
				dataIndex: "paperNum",
				key: "paperNum",
				title: t('order-manage.title.paperNum')
			},
			{
				dataIndex: "localPhone",
				key: "localPhone",
				title: t('order-manage.title.localPhone')
			},
		]
		modalConfig.courseColumns = [{
				dataIndex: "cbiId",
				key: "cbiId",
				title: t('order-manage.openDialog.courseCode')
			},
			{
				dataIndex: "cbiName",
				key: "cbiName",
				title: t('order-manage.openDialog.courseName')
			},
			{
				dataIndex: "projectName",
				key: "projectName",
				title: t('order-manage.openDialog.projectName')
			},
			{
				dataIndex: "semesterName",
				key: "semesterName",
				title: t('order-manage.openDialog.semester')
			},
			{
				dataIndex: "taName",
				key: "taName",
				title: 'TA'
			},
			{
				dataIndex: "professorName",
				key: "professorName",
				title: '教授'
			},
			// {
			// 	dataIndex: "credit",
			// 	key: "credit",
			// 	title: t('order-manage.openDialog.credit')
			// },
		]
		modalConfig.saleColumns = [
			{
        title: t("preferentialAllocation.label.preferentialName"),
        dataIndex: "preName",
        width: 160,
        key: "preName",
        ellipsis: true,
      },
      {
        title: t("preferentialAllocation.label.offerStartTime"),
        dataIndex: "preBtime",
        key: "preBtime",
        width: 160,
        ellipsis: true,
        cellRender: (record, data) => {
          return data ? moment(data).format("YYYY-MM-DD HH:mm:ss") : '';
        },
      },
      {
        title: t("preferentialAllocation.label.offerEndTime"),
        dataIndex: "preEtime",
        key: "preEtime",
        width: 160,
        ellipsis: true,
        cellRender: (record, data) => {
          return data ? moment(data).format("YYYY-MM-DD HH:mm:ss") : '';
        },
      },
			{
        title: t("preferentialAllocation.label.preferenceType"),
        dataIndex: "preType",
        key: "preType",
        width: 130,
        cellRender: (record, data) => {
          const item = dictLists.data[dictEnum.PRE_TYPE]
            ? dictLists.data[dictEnum.PRE_TYPE].find((v) => v.value == data)
            : {};
          return item ? item.label : "";
        },
      },
			{
        title: t("preferentialAllocation.label.preferentialAmount"),
        dataIndex: "preAmt",
        key: "preAmt",
        width: 120,
      },
      {
        title: t("preferentialAllocation.label.state"),
        dataIndex: "preStatus",
        key: "preStatus",
        width: 100,
        cellRender: (record, data) => {
          return data == 1 ? "启用" : "禁用";
        },
      },
      {
        title: t("preferentialAllocation.label.creator"),
        dataIndex: "createBy",
        key: "createBy",
        width: 130,
      },
		]
		modalConfig.saleSearchForm = [
			{
				key: "preName",
				type: "input",
				label: t("preferentialAllocation.label.preferentialName"),
				placeholder: "请输入",
			},
			{
				key: "preType",
				type: "select",
				label: t("preferentialAllocation.label.preferenceType"),
				options: dictLists.data[dictEnum.PRE_TYPE],
				placeholder: "请选择",
			},
			{
				key: "courseType",
				type: "select",
				label: t("preferentialAllocation.label.typesOfPreferentialCourses"),
				options: dictLists.data[dictEnum.COURSE_TYPE],
				placeholder: "请选择",
			},
		]
		modalConfig.depositColumns = [{
				dataIndex: "id",
				key: "id",
				title: "订单号"
			},
			{
				dataIndex: "createTime",
				key: "createTime",
				title: "提交时间"
			},
			{
				dataIndex: "deductionStatus",
				key: "deductionStatus",
				title: "状态"
			}
		]
	})
	const detele = sendIndex => {
		formState.state.orderCourseList.splice(sendIndex, 1)
		formState.state.orderPolicyList = [];
	}
	const detelesale = sendIndex => {
		formState.state.orderPolicyList.splice(sendIndex, 1)
	}
	const resetForm = () => {
		formState.state = {
			stuId: '',
			stuName: '',
			colName: '',
			localPhone: '',
			paperNum: '',
			orderPolicyList: [],
			buspId: '',
			isSpecial: '0',
			orderCourseList: [],
			orderType: '手工录入',
			payChn: "2",
			status: '0',
			recAmt:'',//定金金额
			specialAmt: '', //特殊优惠金额
			prePolicy: '', //优惠政策
			totalAmt: '0', //课程总价,
			preAmt: '0', //优惠总金额,
			receivableTotalAmt: '0', //应收金额
		}
		formRef.value.resetFields()
	}
	const onSubmit = () => {
		if (!formState.state.buspId) {
			return message.warning('请先选择学生')
		}
		formRef.value.validate().then(() => {
			isLoading = true;
			formState.state.prePolicy = '';
			if (formState.state.orderPolicyList.length > 0) {
				formState.state.orderPolicyList.forEach(function(value) {
					if (value.preName) {
						formState.state.prePolicy += value.preName + ','
					}
				})
				formState.state.prePolicy = formState.state.prePolicy.substring(0, formState.state.prePolicy
					.length - 1);
			}
			console.log(formState.state)
			if (route.query.id) {
				updateItem(formState.state)
			} else {
				saveItem(formState.state)
			}
		})
	};

	const saveItem = (data) => {
		save(data).then(res => {
			if (res.code === 200) {
				message.success('保存成功')
				router.push({
					path: '/studentrtv/order-manage/collection',
					query: { ...res.data }
				})
			}
			if (res.code === 500) return message.error(res.msg || '新增失败，服务器错误')
			isLoading = false
		}).catch(() => isLoading = false)
	}
	const updateItem = (data) => {
		update(data).then(res => {
			if (res.code === 200) {
				message.success('保存成功')
				router.push({
					path: '/studentrtv/order-manage/collection',
					query: { ...res.data }
				})
			}
			if (res.code === 500) return message.error(res.msg || '编辑失败，服务器错误')
			isLoading = false
		}).catch(() => isLoading = false)
	}

	const openDialog = (type) => {
		modalConfig.currentType = type
		modalConfig.show = true
		modalConfig.selection = false
		modalConfig.searchParams = {}
		modalConfig.searchForm = []
		modalConfig.keys = []
		modalConfig.okText = '关闭'
		let arr = []
		let key = ''
		if (type === 'student') {
			modalConfig.isPagination = true
			modalConfig.commonColumns = modalConfig.studentColumns
			modalConfig.api = studentpage
			modalConfig.title = t('order-manage.title.selectstu')
			modalConfig.searchForm = modalConfig.studentSearchForm

		} else if (type === 'course') {
			modalConfig.isPagination = true
			modalConfig.commonColumns = modalConfig.courseColumns
			modalConfig.api = coursePage
			modalConfig.title = t('order-manage.openDialog.selectcourse')
			modalConfig.searchForm = modalConfig.courseSearchForm
			modalConfig.selection = true
			modalConfig.okText = '确认'
			arr =	formState.state.orderCourseList || []
			key = 'courseId'
		} else if (type === 'sale') {
			if (formState.state.orderCourseList.length > 0) {
				modalConfig.isPagination = false
				let courseIds = formState.state.orderCourseList.map(item => item.courseId)
				const searchParams = {
					currentTime: new Date(),
					orderCourseIds: courseIds
				};
				modalConfig.commonColumns = modalConfig.saleColumns
				modalConfig.api = salepage
				modalConfig.searchParams = searchParams
				modalConfig.selection = true
				modalConfig.searchForm = modalConfig.saleSearchForm
				modalConfig.title = '选择优惠'
				modalConfig.okText = '确认'
				arr = formState.state.orderPolicyList || []
				key = 'policyId'
			} else {
				modalConfig.show = false
				message.error({
					content: '请选择课程'
				})
			}
		} else if (type === 'Deposit') {
			modalConfig.isPagination = true
			modalConfig.commonColumns = modalConfig.depositColumns
			modalConfig.api = depositPage
			modalConfig.title = t('order-manage.title.selectdeposit')
			modalConfig.searchForm = ''
		}
		
		if (!key) return
		modalConfig.keys = arr.map(item => item[key])
	}
	const closeDialog = () => {
		modalConfig.show = false
	}
	const selectItem = (value, type) => {
		if (type === 'student') {
			formState.state.buspId = value.id
			formState.state.stuName = value.stuName
			formState.state.colName = value.colName
			formState.state.paperNum = value.paperNum
			formState.state.localPhone = value.localPhone
		} else if (type === 'course') {
			if (value.data && Array.isArray(value.data)) {
				let ids = []
				let newArr = []
				value.data.forEach(item => {
					ids.push(item.id)
					if (!modalConfig.keys.includes(item.id)) {
						newArr.push({
							credit: item.credit,
							courseId: item.id,
							courseName: item.cbiName,
							price: item.price,
							professorId: item.professorId,
							professorName: item.professorName,
							projectId: item.projectId,
							projectName: item.projectName,
							schId: item.schId,
							schName: item.schName,
							schShiftCode: item.schShiftCode,
							semesterId: item.semesterId,
							semesterName: item.semesterName,
							shiftCode: item.shiftCode,
							shiftId: item.shiftId,
							stuId: item.stuId,
							taId: item.taId,
							taName: item.taName,
							courSts: item.state, // 认证状态
							creditSts: '', // 上课状态
							regSts: '', // 转学分状态
						});
					}
				})
				newArr.unshift(...formState.state.orderCourseList)
				formState.state.orderCourseList = newArr.filter(i => ids.includes(i.courseId))
				formState.state.orderPolicyList = [];
			}
			modalConfig.selection = false
		} else if (type === 'sale') {
			if (value.data && Array.isArray(value.data)) {
				value.data.forEach(item => {
					if (modalConfig.keys.includes(item.id)) return
					formState.state.orderPolicyList.push({
						policyId: item.id,
						policyName: item.preName,
						preType: item.preType,
						preBtime: item.preBtime,
						preEtime: item.preEtime,
						policyAmount: item.preAmt
					});
				})
			}
		}
	}
	const formatter = (value) => {
		if (!value) return ''
		const obj = dictLists.data[dictEnum.PRE_TYPE] && dictLists.data[dictEnum.PRE_TYPE].find(item => item.value == value)
		return obj ? obj.label : ''
	}
	const validatorSprice = (rules, value, callback) => {
		if (value && parseFloat(formState.state.receivableTotalAmt) < 0) {
			return Promise.reject('特殊优惠金额应小于应付总额')
		}
		return Promise.resolve()
	}
	//计算价格
	// const price = () => {
	// 	formState.state.totalAmt = 0;
	// 	formState.state.preAmt = 0;
	// 	formState.state.receivableTotalAmt = 0;
	// 	formState.state.orderCourseList.forEach(function(value) {
	// 		formState.state.totalAmt += value.price
	// 	})
	// 	formState.state.orderPolicyList.forEach(function(value) {
	// 		formState.state.preAmt += value.discount
	// 	})
	// 	formState.state.receivableTotalAmt = formState.state.totalAmt - formState.state.preAmt;
	// }
</script>
<style scoped>
	.pre-title {
		padding: 10px 25px;
		background-color: #f5f5f5;
		color: #555;
	}

	.red {
		color: red;
		font-size: 20px;
	}
</style>
